import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/pages/login_page.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/utils.dart';

class MyPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<MyPage> {
  Map userInfo = {};
  String username = '';
  bool loadSuccess = false;

  @override
  void initState() {
    super.initState();
    getUserInfo();
  }

  /**
   * @description: 获取用户信息
   * @return {*}
   */
  getUserInfo() {
    Utils.getUserId().then((userId) => {
          DioUtils.request("common/getDetails",
              context: context,
              method: "POST",
              params: {'id': userId}, onSuccess: (res) {
            if (res['code'] == 1) {
              setState(() {
                loadSuccess = true;
                userInfo = res['data'];
                username = res['data']['username'];
              });
            } else {
              Utils.showText(text: res['msg']);
            }
          }, onError: (error) {
            // Toast.show(error);
          })
        });
  }

  Widget _buildBackground() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        width: 750.w,
        height: 450.w,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/my_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  Widget _buildAvatar() {
    if (loadSuccess) {
      if (userInfo['avatar'].toString().isNotEmpty) {
        return Image.network(DioUtils.API_PREFIX + userInfo['avatar'],
            width: 120.w, height: 120.w, fit: BoxFit.cover);
      } else {
        return Image.asset('assets/avatar.png', width: 120.w, height: 120.w);
      }
    } else {
      return Container(
        width: 120.w,
        height: 120.w,
        color: Utils.hexToColor('#F1F3F4'),
      );
    }
  }

  Widget _buildUserInfo() {
    final double statusBarHeight = MediaQuery.of(context).padding.top;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          width: double.infinity,
          height: statusBarHeight,
        ),
        InkWell(
          focusColor: Colors.red,
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(25.w, 29.w, 45.w, 29.w),
            child: Image.asset(
              'assets/arrow_return.png',
              width: 17.w,
            ),
          ),
        ),
        Align(
          child: Container(
            width: double.infinity,
            height: 130.w,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                    margin: EdgeInsets.fromLTRB(40.w, 5.w, 0.w, 0),
                    child: Hero(
                      tag: 'avatar',
                      child: Container(
                          width: 120.w,
                          height: 120.w,
                          decoration: BoxDecoration(
                            border:
                                new Border.all(color: Colors.white, width: 4.w),
                            borderRadius: BorderRadius.circular(120.w),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(120.w),
                            child: _buildAvatar(),
                          )),
                    )),
                Container(
                  margin: EdgeInsets.only(left: 20.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        loadSuccess == true ? userInfo['name'] : '',
                        maxLines: 1,
                        style: TextStyle(color: Colors.white, fontSize: 36.w),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 10.w),
                        child: Text(
                          '部门：' +
                              (loadSuccess == true
                                  ? userInfo['department_name']
                                  : ''),
                          maxLines: 1,
                          style: TextStyle(
                              color: Utils.hexToColor('#88B7FF'),
                              fontSize: 12,
                              height: 1),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildItem(context) {
    int index = 0;
    List<Widget> widget = [];
    List list = [
      {
        "icon": "assets/my_icon1.png",
        "title": "个人中心",
        "route": "/personal_center"
      },
      {
        "icon": "assets/my_icon2.png",
        "title": "修改密码",
        "route": "/update_password"
      },
      {"icon": "assets/my_icon3.png", "title": "消息通知", "route": "/message"},
    ];

    for (var item in list) {
      index++;
      widget.add(Column(
        children: <Widget>[
          InkWell(
            onTap: () {
              Navigator.pushNamed(context, item['route']);
            },
            child: Container(
              height: 142.w,
              padding: EdgeInsets.fromLTRB(32.w, 0, 76.w, 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(children: <Widget>[
                    Image.asset(item['icon'], width: 62.w, height: 62.w),
                    Container(
                      padding: EdgeInsets.only(bottom: 4.w),
                      margin: EdgeInsets.only(left: 27.w),
                      child: Text(item['title'],
                          style: TextStyle(
                              color: Utils.hexToColor('#333333'),
                              fontSize: 16)),
                    )
                  ]),
                  Image.asset('assets/arrow_r_n.png', width: 13.w),
                ],
              ),
            ),
          ),
          Offstage(
            offstage: index == 3 ? true : false,
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(color: Utils.hexToColor('#F7F7F7')))),
            ),
          )
        ],
      ));
    }

    return Column(children: widget);
  }

  Widget _buildLogOutButton() {
    return Hero(
        tag: 'btn',
        child: Container(
            width: 700.w,
            height: 100.w,
            margin: EdgeInsets.only(top: 40.w),
            child: ElevatedButton(
                onPressed: () {
                  Utils.openAlert('确定退出当前账号吗？', context).then((confirm) {
                    if (confirm) {
                      Utils.logOut();
                      Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(builder: (context) => LoginPage()),
                          (route) => route == null);
                    }
                  });
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(20.w))),
                ),
                child: Text('退出登录',
                    style: TextStyle(
                        color: Utils.hexToColor('#FA5450'), fontSize: 16)))));
  }

  Widget build(BuildContext content) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        body: Container(
            height: double.infinity,
            color: Utils.hexToColor('#F5F6FA'),
            child: SingleChildScrollView(
                child: Stack(children: <Widget>[
              _buildBackground(),
              _buildUserInfo(),
              Center(
                  child: Container(
                      margin: EdgeInsets.only(top: 320.w),
                      child: Column(children: <Widget>[
                        Container(
                            width: 700.w,
                            height: 432.w,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(20.w)),
                            child: _buildItem(context)),
                        _buildLogOutButton()
                      ])))
            ]))));
  }
}
